

import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import Layout from '../../components/Layout';
import authApi from '../../api/auth';
import studentApi, { MyCourseFormDto } from '../../api/student';

interface CourseData {
  id: string;
  title: string;
  description: string;
  instructor: string;
  instructorAvatar: string;
  duration: string;
  progress: number;
  status: 'active' | 'completed' | 'ended';
  lastStudyDate: string;
  coverImage: string;
}

const EnrolledCoursesPage: React.FC = () => {
  const navigate = useNavigate();
  
  // 课程数据状态
  const [coursesData, setCoursesData] = useState<CourseData[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string>('');

  // 搜索和筛选状态
  const [courseSearchTerm, setCourseSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [sortBy, setSortBy] = useState('recent');
  const [filteredCourses, setFilteredCourses] = useState<CourseData[]>(coursesData);

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '我的课程 - 学途';
    return () => { document.title = originalTitle; };
  }, []);

  // 拉取后端“我的报名课程”数据
  useEffect(() => {
    const fetchEnrolledCourses = async () => {
      try {
        setLoading(true);
        setError('');
        const token = localStorage.getItem('token');
        if (!token) {
          setError('需要登录才能查看已报名课程');
          setLoading(false);
          return;
        }

        const userResp = await authApi.getUser();
        const userId = userResp?.data?.id;
        if (!userId) {
          setError('未获取到用户信息');
          setLoading(false);
          return;
        }

        const resp = await studentApi.getEnrolledCourses(userId);
        const list: MyCourseFormDto[] = resp?.data || [];

        // 将后端数据映射为页面展示所需结构
        const mapped: CourseData[] = list.map(item => ({
          id: String(item.courseId),
          title: item.courseName || '未命名课程',
          description: '报名记录来源于 course_form',
          instructor: '授课教师待定',
          instructorAvatar: 'https://s.coze.cn/image/mvcrMM0jD-E/',
          duration: '—',
          progress: item.isPaid === 1 ? 100 : 0,
          status: item.isPaid === 1 ? 'completed' : 'active',
          lastStudyDate: item.createTime ? String(item.createTime).slice(0, 10) : '—',
          coverImage: 'https://s.coze.cn/image/RcIuiLf8cfg/'
        }));

        setCoursesData(mapped);
      } catch (err: any) {
        console.error('获取已报名课程失败:', err);
        setError(err?.message || '获取已报名课程失败');
      } finally {
        setLoading(false);
      }
    };

    fetchEnrolledCourses();
  }, []);

  // 筛选和排序课程
  useEffect(() => {
    let filtered = coursesData.filter(course => {
      const matchesSearch = courseSearchTerm === '' || 
        course.title.toLowerCase().includes(courseSearchTerm.toLowerCase());
      
      const matchesStatus = statusFilter === '' || course.status === statusFilter;
      
      return matchesSearch && matchesStatus;
    });

    // 排序
    filtered.sort((a, b) => {
      switch(sortBy) {
        case 'recent':
          return new Date(b.lastStudyDate).getTime() - new Date(a.lastStudyDate).getTime();
        case 'progress':
          return b.progress - a.progress;
        case 'name':
          return a.title.localeCompare(b.title);
        case 'date':
        default:
          return 0;
      }
    });

    setFilteredCourses(filtered);
  }, [courseSearchTerm, statusFilter, sortBy, coursesData]);

  // 处理课程卡片点击
  const handleCourseCardClick = (courseId: string) => {
    navigate(`/course-detail?courseId=${courseId}`);
  };

  // 处理快速学习按钮点击
  const handleQuickLearnClick = (e: React.MouseEvent, courseId: string) => {
    e.stopPropagation();
    navigate(`/course-detail?courseId=${courseId}&action=learn`);
  };



  // 获取状态标签样式和文本
  const getStatusInfo = (status: string) => {
    switch(status) {
      case 'active':
        return { className: 'bg-blue-100 text-blue-800', text: '进行中' };
      case 'completed':
        return { className: 'bg-green-100 text-green-800', text: '已完成' };
      case 'ended':
        return { className: 'bg-gray-100 text-gray-800', text: '已结课' };
      default:
        return { className: '', text: '' };
    }
  };

  // 获取进度条样式
  const getProgressBarStyle = (status: string, progress: number) => {
    if (status === 'completed' || status === 'ended') {
      return { width: '100%', className: 'bg-green-500' };
    }
    return { width: `${progress}%`, className: 'bg-blue-500' };
  };

  // 获取按钮文本和样式
  const getButtonInfo = (status: string) => {
    switch(status) {
      case 'active':
        return { 
          text: '继续学习', 
          className: 'px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors' 
        };
      case 'completed':
        return { 
          text: '查看证书', 
          className: 'px-4 py-2 bg-gray-100 text-gray-900 rounded-lg hover:bg-gray-200 transition-colors' 
        };
      case 'ended':
        return { 
          text: '已结课', 
          className: 'px-4 py-2 bg-gray-100 text-gray-900 rounded-lg hover:bg-gray-200 transition-colors' 
        };
      default:
        return { text: '', className: '' };
    }
  };

  // 获取日期标签文本
  const getDateLabelText = (status: string, date: string) => {
    switch(status) {
      case 'active':
        return `最近学习：${date}`;
      case 'completed':
        return `完成时间：${date}`;
      case 'ended':
        return `结课时间：${date}`;
      default:
        return date;
    }
  };

  // 计算课程统计数据
  const totalCourses = coursesData.length;
  const activeCourses = coursesData.filter(course => course.status === 'active').length;
  const completedCourses = coursesData.filter(course => course.status === 'completed').length;

  return (
    <Layout title="已报名课程 - 学途">
      <div className="flex min-h-screen bg-gray-50">
        {/* 左侧菜单 */}
        <aside className="w-64 bg-white border-r border-gray-200 min-h-screen">
          <nav className="p-4">
            {/* 个人中心菜单 */}
            <div>
              <Link to="/personal-center" className="flex items-center space-x-3 px-4 py-3 mb-4 text-gray-600 hover:bg-gray-50 hover:text-blue-600 rounded-lg transition-colors">
                <i className="fas fa-user text-lg"></i>
                <span className="font-medium">个人中心</span>
              </Link>
              <ul className="space-y-1">
                <li>
                  <Link to="/personal-info" className="flex items-center space-x-3 px-4 py-2 text-gray-600 hover:bg-gray-50 hover:text-blue-600 rounded-lg text-sm transition-colors">
                    <i className="fas fa-user-edit text-base"></i>
                    <span>个人信息</span>
                  </Link>
                </li>
                <li>
                  <Link to="/enrolled-courses" className="flex items-center space-x-3 px-4 py-2 bg-blue-50 text-blue-600 rounded-lg text-sm transition-colors">
                    <i className="fas fa-book-open text-base"></i>
                    <span>已报名课程</span>
                  </Link>
                </li>
                <li>
                  <Link to="/messages" className="flex items-center space-x-3 px-4 py-2 text-gray-600 hover:bg-gray-50 hover:text-blue-600 rounded-lg text-sm transition-colors">
                    <i className="fas fa-envelope text-base"></i>
                    <span>站内信</span>
                  </Link>
                </li>
                <li>
                  <Link to="/account-security" className="flex items-center space-x-3 px-4 py-2 text-gray-600 hover:bg-gray-50 hover:text-blue-600 rounded-lg text-sm transition-colors">
                    <i className="fas fa-shield-alt text-base"></i>
                    <span>账户安全</span>
                  </Link>
                </li>
              </ul>
            </div>
          </nav>
        </aside>

        {/* 主内容区域 */}
        <main className="flex-1 min-w-0">
          <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
            {/* 页面头部 */}
            <div className="mb-8">
              <div className="flex items-center justify-between">
                <div>
                  <h1 className="text-3xl font-bold text-gray-900 mb-2">我的课程</h1>
                  <nav className="text-sm text-gray-600">
                    <Link to="/home" className="hover:text-blue-600 transition-colors">首页</Link>
                    <span className="mx-2">/</span>
                    <Link to="/personal-center" className="hover:text-blue-600 transition-colors">个人中心</Link>
                    <span className="mx-2">/</span>
                    <span className="text-gray-900">已报名课程</span>
                  </nav>
                </div>
                <div className="bg-white rounded-xl shadow-lg p-4">
                  <div className="grid grid-cols-3 gap-4 text-center">
                    <div>
                      <div className="text-2xl font-bold text-blue-600">{totalCourses}</div>
                      <div className="text-sm text-gray-600">总课程</div>
                    </div>
                    <div>
                      <div className="text-2xl font-bold text-green-600">{activeCourses}</div>
                      <div className="text-sm text-gray-600">进行中</div>
                    </div>
                    <div>
                      <div className="text-2xl font-bold text-indigo-600">{completedCourses}</div>
                      <div className="text-sm text-gray-600">已完成</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* 工具栏区域 */}
            <div className="bg-white rounded-xl shadow-lg p-6 mb-6">
              <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-4 lg:space-y-0">
                {/* 搜索框 */}
                <div className="flex-1 max-w-md">
                  <div className="relative">
                    <input 
                      type="text" 
                      placeholder="搜索课程名称..." 
                      value={courseSearchTerm}
                      onChange={(e) => setCourseSearchTerm(e.target.value)}
                      className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    />
                    <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                  </div>
                </div>
                
                {/* 筛选器 */}
                <div className="flex items-center space-x-4">
                  <div className="flex items-center space-x-2">
                    <label htmlFor="status-filter" className="text-sm text-gray-600">状态：</label>
                    <select 
                      id="status-filter"
                      value={statusFilter}
                      onChange={(e) => setStatusFilter(e.target.value)}
                      className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                      <option value="">全部</option>
                      <option value="active">进行中</option>
                      <option value="completed">已完成</option>
                      <option value="ended">已结课</option>
                    </select>
                  </div>
                  
                  <div className="flex items-center space-x-2">
                    <label htmlFor="sort-filter" className="text-sm text-gray-600">排序：</label>
                    <select 
                      id="sort-filter"
                      value={sortBy}
                      onChange={(e) => setSortBy(e.target.value)}
                      className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                      <option value="recent">最近学习</option>
                      <option value="progress">学习进度</option>
                      <option value="name">课程名称</option>
                      <option value="date">报名时间</option>
                    </select>
                  </div>
                </div>
              </div>
            </div>

            {/* 提示与加载 */}
            {error && (
              <div className="bg-red-50 text-red-700 border border-red-200 rounded-lg p-3 mb-4">
                {error}
              </div>
            )}
            {loading && (
              <div className="bg-white rounded-xl shadow p-6 mb-4 text-gray-600">正在加载我的报名课程...</div>
            )}

            {/* 课程列表 */}
            <div className="space-y-6 mb-8">
              {filteredCourses.map((course) => {
                const statusInfo = getStatusInfo(course.status);
                const progressBarStyle = getProgressBarStyle(course.status, course.progress);
                const buttonInfo = getButtonInfo(course.status);
                
                return (
                  <div 
                    key={course.id}
                    onClick={() => handleCourseCardClick(course.id)}
                    className="bg-white rounded-xl shadow-lg hover:shadow-xl transition-all overflow-hidden cursor-pointer"
                  >
                    <div className="flex">
                      <img 
                        src={course.coverImage} 
                        alt={`${course.title}课程封面`} 
                        className="w-32 h-32 object-cover"
                      />
                      <div className="flex-1 p-6">
                        <div className="flex items-start justify-between mb-3">
                          <div className="flex-1">
                            <h3 className="text-lg font-semibold text-gray-900 mb-2">{course.title}</h3>
                            <p className="text-gray-600 text-sm mb-3">{course.description}</p>
                          </div>
                          <span className={`${statusInfo.className} px-3 py-1 rounded-full text-sm font-medium ml-4`}>
                            {statusInfo.text}
                          </span>
                        </div>
                        
                        <div className="flex items-center space-x-4 mb-3">
                          <div className="flex items-center space-x-2">
                            <img 
                              src={course.instructorAvatar} 
                              alt={`${course.instructor}头像`} 
                              className="w-6 h-6 rounded-full"
                            />
                            <span className="text-gray-600 text-sm">{course.instructor}</span>
                          </div>
                          <div className="text-gray-600 text-sm">
                            <i className="fas fa-clock mr-1"></i>
                            {course.duration}
                          </div>
                        </div>
                        
                        {/* 进度条 */}
                        <div className="mb-4">
                          <div className="flex justify-between items-center mb-2">
                            <span className="text-sm text-gray-600">学习进度</span>
                            <span className={`text-sm font-medium ${course.status === 'active' ? 'text-blue-600' : 'text-green-600'}`}>
                              {course.progress}%
                            </span>
                          </div>
                          <div className="w-full bg-gray-200 rounded-full h-2">
                            <div 
                              className={`${progressBarStyle.className} h-2 rounded-full`} 
                              style={{ width: progressBarStyle.width }}
                            ></div>
                          </div>
                        </div>
                        
                        <div className="flex items-center justify-between">
                          <div className="text-gray-600 text-sm">
                            <i className="fas fa-calendar mr-1"></i>
                            {getDateLabelText(course.status, course.lastStudyDate)}
                          </div>
                          <button 
                            onClick={(e) => handleQuickLearnClick(e, course.id)}
                            className={`${buttonInfo.className} text-sm font-medium`}
                          >
                            {buttonInfo.text}
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>

            {/* 分页区域 */}
            <div className="bg-white rounded-xl shadow-lg p-4">
              <div className="flex items-center justify-between">
                <div className="text-sm text-gray-600">
                  显示第 <span className="font-medium">1</span> 到 <span className="font-medium">{filteredCourses.length}</span> 条，共 <span className="font-medium">{filteredCourses.length}</span> 条记录
                </div>
                
                <div className="flex items-center space-x-2">
                  <button 
                    className="px-3 py-2 text-sm border border-gray-300 rounded-lg text-gray-600 hover:bg-gray-50 transition-colors" 
                    disabled
                  >
                    <i className="fas fa-chevron-left mr-1"></i>
                    上一页
                  </button>
                  
                  <div className="flex space-x-1">
                    <button className="px-3 py-2 text-sm bg-blue-600 text-white rounded-lg">1</button>
                  </div>
                  
                  <button 
                    className="px-3 py-2 text-sm border border-gray-300 rounded-lg text-gray-600 hover:bg-gray-50 transition-colors" 
                    disabled
                  >
                    下一页
                    <i className="fas fa-chevron-right ml-1"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </main>
      </div>
    </Layout>
  );
};

export default EnrolledCoursesPage;

